//
//  SwipeUpInteractiveTransition.m
//  VCTransitionDemo
//
//  Created by 赵国腾 on 16/4/25.
//  Copyright © 2016年 赵国腾. All rights reserved.
//

#import "SwipeUpInteractiveTransition.h"

@interface SwipeUpInteractiveTransition ()

@property (nonatomic, strong) UIViewController *presentingVC;
@property (nonatomic, assign) BOOL shouldComplete;

@end

@implementation SwipeUpInteractiveTransition

- (void)wireToViewController:(UIViewController *)viewController {
    
    self.presentingVC = viewController;
    [self prepareGestureRecognizerInView:viewController.view];
}

- (void)prepareGestureRecognizerInView:(UIView *)view {
    
    UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    
    [view addGestureRecognizer:gesture];
}

// 完成速度
- (CGFloat)completionSpeed {
    return 1 - self.percentComplete;
}

// 手势方法
- (void)handleGesture:(UIPanGestureRecognizer *)gestureRecognizer {
    CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view.superview];
    
    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:{
            
            self.interacting = YES;
            [self.presentingVC dismissViewControllerAnimated:YES completion:nil];
            
            break;
        }
            
        case UIGestureRecognizerStateChanged:{
            
            CGFloat fraction = translation.y / 400.0;
            
            fraction = fminf(fmaxf(fraction, 0.0), 1.0);
            self.shouldComplete = (fraction > 0.5);
            
            [self updateInteractiveTransition:fraction];
            break;
        }
            
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:{
            
            self.interacting = NO;
            
            if (!self.shouldComplete || gestureRecognizer.state == UIGestureRecognizerStateCancelled) {
                
                [self cancelInteractiveTransition];
            }else {
            
                [self finishInteractiveTransition];
            }
            
            break;
        }
            
        default:
            break;
    }
    
}

@end












